package com.gdit.zax.thread;

import java.sql.Connection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.gdit.zax.dao.RemindDao;
import com.gdit.zax.dao.UserDao;
import com.gdit.zax.entitys.PushMsg;
import com.gdit.zax.entitys.Remind;
import com.gdit.zax.entitys.UserInfo;
import com.gdit.zax.factory.DAOFactory;
import com.gdit.zax.utils.DBUtil;
import com.gdit.zax.utils.DateUtil;
import com.gdit.zax.utils.LogUtil;

/**
 * 提醒线程
 * 
 * @author lenovo
 * 
 */
public class LoopRemindThread extends Thread {
	private static Map<Integer, RemindThread> rmap = new HashMap<Integer, RemindThread>();

	@Override
	public void run() {
		try {
			sleep((long) (Math.random() * 10 * 1000));// 0-10分钟

			Connection conn = null;
			while (conn == null) {
				LogUtil.print("conn is null");
				conn = DBUtil.getConnection();
				sleep(5000);
			}

			DAOFactory dao = DAOFactory.init(conn, null, null);
			RemindDao rdao = dao.getRemindDao();
			UserDao udao = dao.getUserDao();

			List<Remind> list = rdao.listRemid(1, 10000);
			for (Remind remind : list) {
				Date now = new Date();
				String notitime = (1900 + now.getYear()) + "-"
						+ (now.getMonth() + 1) + "-" + now.getDate() + " "
						+ remind.getTime();
				long waittime = DateUtil.getDate(notitime, null).getTime()
						- System.currentTimeMillis();

				if (waittime > 0) {
					PushMsg msg = new PushMsg();
					msg.setWaittime(waittime);
					msg.setTitle("提醒学习:" + remind.getPlan());
					msg.setContent("内容:" + remind.getTheme());
					UserInfo uinfo = udao.getInfo(remind.getUserid());
					if (uinfo != null) {

						msg.setDbUserId(uinfo.getDbuserid());

						RemindThread rth = new RemindThread(msg);
						rth.start();

						rmap.put(remind.getId(), rth);
					}
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static boolean stopRemind(int rid) {
		if (rmap == null) {
			rmap = new HashMap<Integer, RemindThread>();
		}
		RemindThread rth = rmap.get(rid);
		if (rth != null) {
			rth.stop();
			return true;
		}
		return false;
	}
}
